﻿/***********
作者：xkhhdx
时间：2010-2-13
用途：主代码，响应地址栏的两个按钮事件
来源：xkhhdx
******************************/

// 我们这里直接定义类变量
var firefive =
{
	char_count_limit : 0,
	debug : false,

	/***********
	本文件最后定义的 onLoad 事件
	******************************/
	onLoad: function()
	{
		// 初始化
		this.initialized = true;
		this.strings = document.getElementById( "firefive-strings" );
		try
		{
			var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService( Components.interfaces.nsIPrefService );
			var branch = prefs.getBranch( "extensions.firefive." );
			firefive.debug = branch.getBoolPref( "debug" );
		}
		catch(e)
		{
		}
	},

	/***********
	XUL 中定义的那个 load 事件
	我们这里只添加事件响应代码
	******************************/
	load: function()
	{
		//document.getElementById( "urlbar" ).addEventListener( "keypress", function( event ){ firefive.url_key_press( event );}, false );
		document.getElementById( "urlbar" ).addEventListener( "focus", function(){ firefive.url_get_focus();}, false );
		var branch = Components.classes["@mozilla.org/preferences-service;1"].getService( Components.interfaces.nsIPrefService ).getBranch( "extensions.firefive." );

		char_count_limit = branch.getIntPref( "char_count_limit" );

		// 首次运行
		// 2010-2-20
		if( branch.getBoolPref( "firstrun" ) == true )
		{
			branch.setBoolPref( "firstrun", false );

			var browser = getBrowser();

			window.openDialog( "chrome://firefive/content/login.xul", "login", "chrome,dialog,centerscreen,titlebar,alwaysraised" );

			// 一秒后弹出说明
			setTimeout(
				function( browser )
				{
					browser.selectedTab = browser.addTab( "chrome://firefive/content/firstrun/firstrun.htm" );
				}, 1000, browser );
		}
	},
	
	/***********
	第一次运行时的帐号配置
	xkhhdx 2010-2-20
	******************************/
	login : function()
	{
		var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService( Components.interfaces.nsIPrefService );
		var branch = prefs.getBranch( "extensions.firefive." );
		var str = Components.classes["@mozilla.org/supports-string;1"]
			.createInstance( Components.interfaces.nsISupportsString );
		str.data = document.getElementById( "textusername" ).value;
		branch.setComplexValue( "pref_username", Components.interfaces.nsISupportsString, str );

		str.data = document.getElementById( "textpassword" ).value;
		branch.setComplexValue( "pref_password", Components.interfaces.nsISupportsString, str );
	},

	/***********
	地址栏获得焦点
	xkhhdx 2010-2-10
	******************************/
	url_get_focus : function()
	{
	},

	/***********
	通过 http 协议与 follow5 服务器通讯
	xkhhdx 2010-2-10
	2010-2-13
	******************************/
	post_update : function( status, _username, _password )
	{
		if( status.length > char_count_limit )
		{
			alert( "消息过长，请保持在" + char_count_limit + "字以下" );
			return false;
		}
		var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService( Components.interfaces.nsIPrefService );
		var branch = prefs.getBranch( "extensions.firefive." );
		var username = branch.getComplexValue( "pref_username", Components.interfaces.nsIPrefLocalizedString ).data;
		var password = branch.getComplexValue( "pref_password", Components.interfaces.nsIPrefLocalizedString ).data;

		var xml = new XMLHttpRequest();
		var update_url = 'http://api.follow5.com/api/statuses/update.json?api_key=D4E840CD9F8C4DEF6FB6CA4A30754ED8'

	/***********
	既然你已经看到了这个了，请麻烦你保护好 api_key，
	并遵守 api_key 的使用规则，谢谢合作
	xkhhdx 2010-2-20
	******************************/

		xml.open( "POST", update_url, false );
		var auth = "Basic " + Base64.encode( username + ':' + password );
		xml.setRequestHeader( 'Authorization', auth );
		xml.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

		xml.onreadystatechange = function( e )
		{
			if( xml.readyState == 4 )
			{
				if( xml.status == 200 )
				{
					alert( xml.responseText );
				}
				else
				{
					alert( "Error loading page\n" );
				}
			}
		};

		xml.send( "status=" + status + "&source=firefive" );

		var response_text = xml.responseText;

		if( response_text == "{}" )
			alert( "有重复的～!\n内容：" + status );
		else
		{
			if( xml.status == 400 )
				alert( "发送失败！\n请检查用户名和密码是否正确" );
			else
			{
				if( response_text.substring( 0, 1 ) == "{" )
					alert( "发送成功～!\n内容：" + status );
				else
					alert( "发送失败！\n请检查用户名和密码是否正确" );
			}
		}

	},

	/***********
	响应地址栏那两个图标的分享按钮
	xkhhdx 2010-2-10
	2010-2-13
	******************************/
	with_url_update : function()
	{
		document.getElementById( "firefive-withurl-update-button" ).src = "chrome://firefive/skin/waiting.gif";

		var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService( Components.interfaces.nsIPrefService );
		var branch = prefs.getBranch( "extensions.firefive." );
		var share_text = branch.getComplexValue( "pref_share_text", Components.interfaces.nsIPrefLocalizedString ).data;
		var text = document.getElementById( "urlbar" ).value;

		share_text = share_text
			.replace( "$url", url_shortener.shorten( content.document.location.toString() ) )
			.replace( "$title", content.document.title.toString() )
			.replace( "$comment", text );

		this.post_update( share_text, "firefive", "asdfghjk" );

		document.getElementById( "firefive-withurl-update-button" ).src = "chrome://firefive/skin/follow5_url.png";

	},

	/***********
	响应地址栏那两个图标的发布按钮
	xkhhdx 2010-2-10
	2010-2-13
	******************************/
	update : function()
	{
		document.getElementById( "firefive-update" ).src = "chrome://firefive/skin/waiting.gif";

		var text = document.getElementById( "urlbar" ).value;
		this.post_update( text, "firefive", "asdfghjk" );

		document.getElementById( "firefive-update" ).src = "chrome://firefive/skin/follow5_mouseon.png";
	},

	/***********
	响应地址栏原始的黑底图标鼠标划过时的图标转换
	xkhhdx 2010-2-10
	******************************/
	icon_moveon : function()
	{
		document.getElementById( "firefive-withurl-update-button" ).hidden = false;
		document.getElementById( 'firefive-update' ).src = "chrome://firefive/skin/follow5_mouseon.png"
		var state_label = document.getElementById( 'firefive-count' )

		state_label.hidden = false;

		var length = this.get_url_count();

		if( length > char_count_limit )
		{
			state_label.style.color = "red";
			state_label.value = "已超过 " + ( length - char_count_limit ) + " 字。";
		}
		else
		{
			state_label.style.color = "green";
			state_label.value = "还可以输入 " + ( char_count_limit - length ) + " 字。";
		}

	},

	/***********
	响应地址栏还原原始的黑底图标
	xkhhdx 2010-2-10
	******************************/
	icon_moveout : function()
	{
		var image = document.getElementById( 'firefive-update' );

		if( image.src.match( /follow5_mouseon\.png/ ) )
		{
			image.src = "chrome://firefive/skin/follow5.png"
		}

		document.getElementById( 'firefive-count' ).hidden = true;
		document.getElementById( "firefive-withurl-update-button" ).hidden = true;
	},

	/***********
	计算地址栏字串的长度
	xkhhdx 2010-2-10
	******************************/
	get_url_count : function()
	{
		var status = document.getElementById( "urlbar" ).value;
		length = status.length;
		return length;
	},

	/***********
	计算地址栏键盘输入响应事件 [废弃]
	xkhhdx 2010-2-10
	******************************/
	url_key_press : function( e )
	{
		//this.icon_moveon();
		// 指定 2 秒后还原，但光标闪一下就调用一次，先注释掉吧 -_-#...
		//firefive.trendTimer = setInterval( function(){ firefive.icon_moveout();clearInterval( firefive.trendTimer );}, 2000 );
	},

	/***********
	自动生成代码
	******************************/
	onMenuItemCommand: function( e )
	{
		var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
																	.getService( Components.interfaces.nsIPromptService );
		promptService.alert( window, this.strings.getString( "helloMessageTitle" ),
																this.strings.getString( "helloMessage" ) );
	},

	onToolbarButtonCommand: function( e )
	{
		// 重用上面的函数，当然也可以修改这里
		firefive.onMenuItemCommand( e );
	}
};

window.addEventListener( "load", firefive.onLoad, false );

